package com.app.worldserver;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.execution.MemoryAwareThreadPoolExecutor;

import com.app.framework.AbstractServer;
import com.app.framework.config.ActionConfigLoader;
import com.app.framework.config.PropConfigLoader;
import com.app.framework.config.ServiceConfigLoader;
import com.app.framework.handler.GameUpstreamHandler;
import com.app.framework.handler.SocketUpstreamHandler;
import com.app.framework.pipelinefactory.GamePipelineFactory;
import com.app.framework.pipelinefactory.SocketPipelineFactory;

public class WorldServer extends AbstractServer {
	
	private WorldServer() {
		
	}
	
	public static void start() throws Exception {
		
		ServiceConfigLoader.getInstance();
			
		ActionConfigLoader.getInstance();
		
		PropConfigLoader.getInstance();
		
		ServerBootstrap bootstrap=new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
		
		MemoryAwareThreadPoolExecutor executor = new MemoryAwareThreadPoolExecutor(500,0,0);
		
		GamePipelineFactory factory = new SocketPipelineFactory(executor,new SocketUpstreamHandler(GameUpstreamHandler.HANDLER_TYPE_SS,false));
		
		bootstrap.setPipelineFactory(factory);
		 
		int port = Integer.parseInt(PropConfigLoader.getInstance().getConfig("socketport").getValue());

		bootstrap.setOption("child.tcpNoDelay", true);//child的属性 是与客户端建立连接的socket的,非child的是服务器负责监听客户端连接的主serversocket的
		
		bootstrap.setOption("child.soLinger", 1);
//		bootstrap.setOption("child.receiveBufferSize", 1048576);
		// Setting this option to a value such as 200, 500 or 1000, tells the TCP stack how long the "accept" queue can be. 
		//If this option is not configured, then the backlog depends on OS setting.
		bootstrap.setOption("backlog", 2000);
		
		Channel c = bootstrap.bind(new InetSocketAddress(port));
//		c.getConfig().setBufferFactory(HeapChannelBufferFactory.getInstance(ByteOrder.LITTLE_ENDIAN));//默认大头,在此可设置
		
		System.out.println("world start on "+port);
	}
	
	public static void main(String[] args) {
		try {
			WorldServer.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
